package volatile1;

import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;

import java.util.concurrent.TimeUnit;

/**
 * @author ZhuQi
 * @ClassName Demo
 * @Date 2022/8/22 14:35
 * @Version 1.0
 * @Description 测试 volatile 可见性
 * 注意:禁止使用 system.out.print 测试多线程。它有所，并且会刷新缓存从主存取值
 */
@Log4j2
public class Demo {

    @SneakyThrows
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        // 开启线程
        myThread.start();
        // 主线程执行
        for (; ; ) {
            if (myThread.isFlag()) {
                log.info("主线程访问到 flag 变量");
            }
        }
    }
}
/**
 * 子线程类
 */
@Log4j2
class MyThread extends Thread {

    private boolean flag = false;
//    private volatile boolean flag = false;

    @Override
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 修改变量值
        flag = true;
        log.info("flag = " + flag);
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
